﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pifagor.IG;
using Pifagor.Exceptions;
using System.Threading.Tasks;

namespace Pifagor.Runtime
{
	public class ParList : IComputableValue
	{	
		ExecutionContext _context;
		IGNode _parListNode;
		Value _value;

		public IComputableValue[] Items { get; private set; }

		internal ParList(ExecutionContext context, IComputableValue[] items)
		{
			_context = context;
			Items = items;
			_value = new Value(this);
		}

		internal ParList(ExecutionContext context, IGNode parListNode)
		{
			_context = context;
			_parListNode = parListNode;
		}

		public Value Compute()
		{
			if (_value == null)
			{
				Items = new IComputableValue[_parListNode.Links.Length];
				for (int i = 0; i < _parListNode.Links.Length; i++)
				{
					var listValueNodeLink = _parListNode.Links[i];
					Items[i] = ComputableFactory.CreateComputable(_context, _context.IG.Nodes[listValueNodeLink.Id]);
				}
				_value = new Value(this);
			}

			return _value;
		}

		public override string ToString()
		{
			if (_value == null)
				throw new RuntimeException("ParList must be computed before one can display it.");
			return "[" + string.Join(", ", Items.Select(item => item.ToString()).ToArray()) + "]";
		}
	}
}
